import { ChangeDetectionStrategy, Component, OnInit, Pipe, PipeTransform, ViewChild } from '@angular/core';
import { map, remove, uniqueId } from 'lodash';
import { DatatableComponent } from '@iux/live';

interface DemoUser {
  id: string;
  name: string;
  age: number;
  expand: boolean;
  random: number;
  disabled: boolean;
}

@Pipe({ name: 'userProp' })
export class UserPropPipe implements PipeTransform {
  transform(value: DemoUser[], exponent: string = 'name') {
    return map(value, item => item[exponent]).join(',');
  }
}
@Component({
  selector: 'app-custom-checkbox',
  templateUrl: './custom-checkbox.component.html',
  styles: [
    `
      .section-info {
        margin-bottom: 16px;
      }
      .operation-group {
        margin-bottom: 16px;
      }
      .operation-group button:first-child {
        margin-right: 16px;
      }
      .custom-checkbox {
        display: flex;
      }
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomCheckboxComponent implements OnInit {
  data: DemoUser[];
  selection: DemoUser[];
  pageSizeOptions = [10, 30, 50, 400];
  @ViewChild(DatatableComponent, { static: true }) lvTable: DatatableComponent;
  constructor() {}

  get isAllCheck() {
    const all = this.lvTable.renderData.length,
      selected = this.lvTable.getRenderSelection().length;
    return selected > 0 && all === selected;
  }
  get isHalfCheck() {
    return !this.isAllCheck && !!this.lvTable.getRenderSelection().length;
  }

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = Array.from({ length: 400 }).map((item, key) => this.initUser(key));
    this.selection = [this.data[0], this.data[1]];
  }

  initUser(key: number) {
    return {
      id: uniqueId('uid'),
      name: `user${key}`,
      age: 10 + key,
      expand: false,
      random: parseInt(`${Math.random() * 100}`, 10),
      disabled: Math.random() > 0.5,
    };
  }

  addRow() {
    this.data = [...this.data, ...[this.initUser(0)]];
  }

  deleteRow(source: DemoUser) {
    const removedRow = remove(this.data, item => item.id === source.id);
    this.data = [...this.data];
    this.lvTable.deleteSelection(removedRow);
  }

  selectionRow(source: DemoUser) {
    this.lvTable.toggleSelection(source);
  }

  isSelected(source: DemoUser) {
    return this.lvTable.isSelected(source);
  }

  toggleSelection() {
    this.isAllCheck ? this.lvTable.clearRenderSelection() : this.lvTable.bulkSelection(this.lvTable.renderData);
  }
}
